<?php

namespace app\index\controller;

use app\common\controller\Frontend;

class Building extends Frontend
{

    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $selectpageFields = '*';
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\newhouse\building\Items;
    }
    public function view($ids){
        // $ids = $this->request->request("id");
        $row=\app\admin\model\newhouse\building\Items::get($ids);
        $this->view->assign("row",$row);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $buildingPictureType = \app\admin\model\newhouse\building\Picturetype::all();
        $this->view->assign('buildingPictureType',$buildingPictureType);

        /// 读取当前值
        $commissionPolicyModel=new \app\admin\model\newhouse\building\Policy;
        $policies = $commissionPolicyModel->where('building_id=' . $ids)->select();

        /// 加载图片
        $picture_values=[];
        $pictures = \app\admin\model\newhouse\building\Pictures::all(['building_id'=>$ids]);
        
        foreach($buildingPictureType as $key=>$value){
            $picture_values['v_' . $value->id] = []; // 初始化
        }
        foreach($pictures as $key=>$value){
            $picture_values['v_' . $value->typeid][]= [$value->path,$value->mem];
        }
        $this->view->assign('pictures', $picture_values);

        /// 所有房产类型
        $buildingTypes = \app\admin\model\newhouse\building\Types::all();
        for($i=0;$i<sizeof($buildingTypes);$i++){
            $buildingTypes[$i]['has'] = "";
            $buildingTypes[$i]['price'] = "";
            $buildingTypes[$i]['commission_policy'] = "";
            foreach($policies as $key1=>$value1){
                if($buildingTypes[$i]->id == $value1->type_id){
                    $buildingTypes[$i]['has'] = "true";
                    $buildingTypes[$i]['price'] = $value1->price;
                    $buildingTypes[$i]['commission_policy'] = $value1->commission_policy;
                    break;
                }
            }
            
        }
        $this->view->assign('buildingTypes',$buildingTypes);
        
        // 楼盘标签
        $label_ids = $row->labels;
        $labels =\app\admin\controller\newhouse\building\Labels::getStrFromIds($label_ids);

        $this->view->assign('labels',$labels);
        return $this->view->fetch();
    }
    /**
     * 楼盘列表
     */
    public function buildingitemslist()
    {
        $this->assign('title','楼盘列表');
        return $this->view->fetch();
    }
    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
       
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {

            $datalist = $this->model->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($this->selectpageFields)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    public function buildingfollows(){
         //当前是否为关联查询
         $this->relationSearch = true;

        $building_id = $this->request->request('building_id');
        $tmpwhere='1=1';
        if(!empty($building_id))
            $tmpwhere .= ' AND building_id=' . $building_id;

        $model=new \app\admin\model\newhouse\building\Follow;
        $list = $model
        ->with(['newhousebuildingitems','admin'])
        ->where($tmpwhere)
        // ->order($sort, $order)
        ->select();

        if(!empty($building_id)){
            $building_item_model =   \app\admin\model\newhouse\building\Items::get($building_id);
            $building_state= $building_item_model->state;
        }else{
            $building_state='';
        }

        $result = array("total" =>sizeof( $list), "rows" => $list,"code"=>1,"building_state"=>$building_state);
        return json($result);
    }  
}
